<template>
  <menu class="fx-menu" :class="{border:border}" :style="menuStyle" v-bind="$attrs">
    <slot></slot>
  </menu>
</template>

<script lang="ts">
import { defineComponent, PropType, provide, computed, onMounted, ref, watch, Ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import mitt, { Emitter } from 'mitt'
import { MenuMitt } from '@/base/menu/menuTypes'

interface MenuProps {
  defaultActive: string;
  border: boolean;
  router: boolean;
  backgroundColor: string;
  activeBackgroundColor: string;
  textColor: string;
  textActiveColor: string;
}

export interface MenuProvideStyle {
  backgroundColor: string;
  activeBackgroundColor: string;
  textColor: string;
  textActiveColor: string;
}

export default defineComponent({
  name: 'FxMenu',
  inheritAttrs: true,
  props: {
    // 默认选中
    defaultActive: {
      type: String as PropType<string>,
      required: true
    },
    // 是否需要边框
    border: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    // 路由模式
    router: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    // 背景色
    backgroundColor: {
      type: String as PropType<string>,
      default: null
    },
    // 背景色选中
    activeBackgroundColor: {
      type: String as PropType<string>,
      default: null
    },
    // 字体颜色
    textColor: {
      type: String as PropType<string>,
      default: null
    },
    // 字体选中颜色
    textActiveColor: {
      type: String as PropType<string>,
      default: null
    }
  },
  setup (props: MenuProps) {
    const Route = useRoute()
    const Router = useRouter()
    // 菜单数据监听
    const menuMitt: Emitter = mitt()
    // 当前选中
    const currentIndex = ref<string>(props.defaultActive)
    // 菜单样式
    const menuStyle = computed(() => {
      return {
        backgroundColor: props.backgroundColor,
        color: props.textColor
      }
    })

    // 处理子菜单点击事件
    const handleMenuItemClick = (event: string | undefined): void => {
      if (event) {
        currentIndex.value = event
        if (props.router) Router.push(event)
      }
    }

    watch(() => Route.path, (val) => {
      currentIndex.value = val
    })

    // 全子孙组件传递当前选中
    provide('defaultActive', computed<string>(() => currentIndex.value))
    // 全组件发布更新选中数据方式
    provide<MenuMitt>('menuMitt', {
      menuMittEmit: menuMitt.emit
    })
    provide<Ref<MenuProvideStyle>>('menuStyle', computed(() => {
      return {
        textColor: props.textColor,
        textActiveColor: props.textActiveColor,
        backgroundColor: props.backgroundColor,
        activeBackgroundColor: props.activeBackgroundColor
      }
    }))

    onMounted(() => {
      // 监听菜单子组件点击事件
      menuMitt.on('menuItemClick', handleMenuItemClick)
      // 初始化跳转默认路由
      if (props.router && props.defaultActive !== '') Router.push(props.defaultActive)
    })

    return {
      menuStyle
    }
  }
})
</script>
